// 顶部导入处
import type { PluginContext, PluginAPI } from '../../../modules/plugin/types';
// 将 type-only 改为值导入，供枚举常量与类型共同使用
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api';

export function activate(context: PluginContext, api: PluginAPI) {
  console.log('Activating sample-plugin...');

  const disposable = api.commands.registerCommand('sample.helloWorld', () => {
    api.window.showInformationMessage('Hello World from Sample Plugin!');
  });
  context.subscriptions.push(disposable);

  // 编辑器 Action
  const actionDisposable = api.editor.registerAction({
    id: 'sample.insertHello',
    label: 'Sample: Insert Hello',
    contextMenuGroupId: 'navigation',
    contextMenuOrder: 1.0,
    run: (editor) => {
      editor.trigger('sample-plugin', 'type', { text: 'Hello from plugin! ' });
    }
  });
  context.subscriptions.push(actionDisposable);

  // 方式1：传统补全面板（下拉建议列表）
  const completionDisposable = api.languages.registerCompletionProvider('javascript', {
    triggerCharacters: ['.', '('],
    provideCompletionItems: (model: any, position: any) => {
      const textUntilPosition = model.getValueInRange({
        startLineNumber: position.lineNumber,
        startColumn: 1,
        endLineNumber: position.lineNumber,
        endColumn: position.column,
      });

      // 计算当前单词范围，CompletionItem 需要 range
      const word = model.getWordUntilPosition(position);
      const range: monaco.IRange = {
        startLineNumber: position.lineNumber,
        startColumn: word.startColumn,
        endLineNumber: position.lineNumber,
        endColumn: word.endColumn,
      };

      const suggestions: monaco.languages.CompletionItem[] = [];

      if (textUntilPosition.includes('console.')) {
        suggestions.push(
          {
            label: 'log',
            kind: monaco.languages.CompletionItemKind.Method,
            insertText: 'log(${1:message})',
            insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            detail: 'console.log() - 输出到控制台',
            documentation: '在控制台输出信息',
            range,
          },
          {
            label: 'error',
            kind: monaco.languages.CompletionItemKind.Method,
            insertText: 'error(${1:message})',
            insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            detail: 'console.error() - 输出错误信息',
            range,
          }
        );
      }

      if (textUntilPosition.includes('document.')) {
        suggestions.push(
          {
            label: 'getElementById',
            kind: monaco.languages.CompletionItemKind.Method,
            insertText: 'getElementById(${1:id})',
            insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            detail: 'document.getElementById() - 根据ID获取元素',
            range,
          },
          {
            label: 'querySelector',
            kind: monaco.languages.CompletionItemKind.Method,
            insertText: 'querySelector(${1:selector})',
            insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            detail: 'document.querySelector() - 根据CSS选择器获取元素',
            range,
          }
        );
      }

      if (textUntilPosition.trim() === '') {
        suggestions.push(
          {
            label: 'function',
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: 'function ${1:name}(${2:params}) {\n\t${3:// TODO: 实现功能}\n}',
            insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            detail: '创建新函数',
            documentation: '定义一个新的JavaScript函数',
            range,
          },
          {
            label: 'const',
            kind: monaco.languages.CompletionItemKind.Keyword,
            insertText: 'const ${1:name} = ${2:value};',
            insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
            detail: '定义常量',
            range,
          }
        );
      }

      return { suggestions };
    }
  });
  context.subscriptions.push(completionDisposable);

  // 方式2：内联补全（ghost text智能文本补充）
  const inlineCompletionDisposable = api.languages.registerInlineCompletionsProvider('javascript', {
    provideInlineCompletions: async (model: any, position: any, context: any, token: any) => {
      const textUntilPosition = model.getValueInRange({
        startLineNumber: position.lineNumber,
        startColumn: 1,
        endLineNumber: position.lineNumber,
        endColumn: position.column,
      });

      const currentLine = model.getLineContent(position.lineNumber);
      const items: monaco.languages.InlineCompletion[] = [];

      // 1. 检测 console.l 模式
      if (textUntilPosition.endsWith('console.l')) {
        items.push({
          insertText: 'og()',
          range: {
            startLineNumber: position.lineNumber,
            startColumn: position.column,
            endLineNumber: position.lineNumber,
            endColumn: position.column,
          }
        });
      }

      // 2. 检测函数定义模式
      if (textUntilPosition.endsWith('function ')) {
        items.push({
          insertText: 'myFunction() {\n\t// TODO: 实现功能\n}',
          range: {
            startLineNumber: position.lineNumber,
            startColumn: position.column,
            endLineNumber: position.lineNumber,
            endColumn: position.column,
          }
        });
      }

      // 3. 检测 if 语句模式
      if (textUntilPosition.endsWith('if (')) {
        items.push({
          insertText: 'condition) {\n\t// TODO: 实现逻辑\n}',
          range: {
            startLineNumber: position.lineNumber,
            startColumn: position.column,
            endLineNumber: position.lineNumber,
            endColumn: position.column,
          }
        });
      }

      // 4. 检测 document.get 模式
      if (textUntilPosition.endsWith('document.get')) {
        items.push({
          insertText: 'ElementById(\'id\')',
          range: {
            startLineNumber: position.lineNumber,
            startColumn: position.column,
            endLineNumber: position.lineNumber,
            endColumn: position.column,
          }
        });
      }

      // 5. 检测简单的变量声明
      if (/^\s*const\s+\w*$/.test(textUntilPosition)) {
        items.push({
          insertText: ' = ',
          range: {
            startLineNumber: position.lineNumber,
            startColumn: position.column,
            endLineNumber: position.lineNumber,
            endColumn: position.column,
          }
        });
      }

      return { items };
    },

    freeInlineCompletions: (_completions: any) => {
      // 清理资源（如果需要）
    },

    handleItemDidShow: (_completions: any, item: any, updatedInsertText: string) => {
      // 处理建议显示事件
      console.log('Inline completion shown:', item);
    },

    handlePartialAccept: (_completions: any, _item: any, acceptedCharacters: number, _info: any) => {
      // 处理部分接受事件
      console.log('Partial accept:', acceptedCharacters);
    }
  });
  context.subscriptions.push(inlineCompletionDisposable);

  // 为 TypeScript 也提供类似功能
  const tsCompletionDisposable = api.languages.registerCompletionProvider('typescript', {
    triggerCharacters: ['.', ':', '('],
    provideCompletionItems: (model: any, position: any) => {
      const word = model.getWordUntilPosition(position);
      const range: monaco.IRange = {
        startLineNumber: position.lineNumber,
        startColumn: word.startColumn,
        endLineNumber: position.lineNumber,
        endColumn: word.endColumn,
      };
      const suggestions: monaco.languages.CompletionItem[] = [
        {
          label: 'interface',
          kind: monaco.languages.CompletionItemKind.Interface,
          insertText: 'interface ${1:Name} {\n\t${2:property}: ${3:type};\n}',
          insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
          detail: '定义TypeScript接口',
          range,
        },
        {
          label: 'type',
          kind: monaco.languages.CompletionItemKind.Keyword,
          insertText: 'type ${1:Name} = ${2:type};',
          insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet,
          detail: '定义类型别名',
          range,
        }
      ];
      return { suggestions };
    }
  });
  context.subscriptions.push(tsCompletionDisposable);

  console.log('Sample plugin activated with intelligent completions!');
}

export function deactivate() {
  console.log('Deactivating sample-plugin...');
}